//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package dao

import (
	"context"

	"atomgit.com/openlinksaas-org/api-server/dao/db_ns"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
)

type MsgDataDBItem struct {
	MsgId        string `bson:"_id"`
	Content      string `bson:"content"`
	CreateUserId string `bson:"createUserId"`
	CreateTime   int64  `bson:"createTime"`
	HasChanged   bool   `bson:"hasChanged"`
}

type _MsgDataDao struct {
	mc *mongo.Collection
}

func newMsgDataDao(db *mongo.Database) (*_MsgDataDao, error) {
	mc := db.Collection(db_ns.DB_NS_GLOBAL + "msg_data")
	return &_MsgDataDao{mc: mc}, nil
}

func (db *_MsgDataDao) Insert(ctx context.Context, dbItem *MsgDataDBItem) error {
	_, err := db.mc.InsertOne(ctx, dbItem)
	return err
}

func (db *_MsgDataDao) Update(ctx context.Context, msgId, content string) error {
	_, err := db.mc.UpdateOne(ctx, bson.M{"_id": msgId}, bson.M{"$set": bson.M{"content": content, "hasChanged": true}})
	return err
}

func (db *_MsgDataDao) Remove(ctx context.Context, msgId string) error {
	_, err := db.mc.DeleteOne(ctx, bson.M{"_id": msgId})
	return err
}

func (db *_MsgDataDao) ListById(ctx context.Context, msgIdList []string) (map[string]*MsgDataDBItem, error) {
	if len(msgIdList) == 0 {
		return map[string]*MsgDataDBItem{}, nil
	}
	cursor, err := db.mc.Find(ctx, bson.M{"_id": bson.M{"$in": msgIdList}})
	if err != nil {
		return nil, err
	}
	tmpList := []*MsgDataDBItem{}
	err = cursor.All(ctx, &tmpList)
	if err != nil {
		return nil, err
	}
	retMap := map[string]*MsgDataDBItem{}
	for _, tmpItem := range tmpList {
		retMap[tmpItem.MsgId] = tmpItem
	}
	return retMap, nil
}

func (db *_MsgDataDao) Get(ctx context.Context, msgId string) (*MsgDataDBItem, error) {
	retItem := &MsgDataDBItem{}
	err := db.mc.FindOne(ctx, bson.M{"_id": msgId}).Decode(retItem)
	return retItem, err
}
